package com.leyou.service;

import com.leyou.dao.BrandMapper;
import com.leyou.pojo.Brand;
import com.leyou.pojo.BrandVo;
import com.leyou.pojo.Category;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {
    @Autowired(required = false)
    private BrandMapper brandMapper;
    public List<Brand> searchBrand(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        Example example = new Example(Brand.class);
        example.setOrderByClause(sortBy + " " + (desc ? "desc" : "asc"));
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)){
            //根据name模糊查询，或者根据首字母查询
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }
        List<Brand> brands = brandMapper.selectByExample(example);
        return brands;
    }

    public void deleteById(Integer id) {
        this.brandMapper.deleteByPrimaryKey(id);
    }

    public void addBrand(Brand brand, String[] split) {
        brandMapper.insertSelective(brand);
        for (String s : split) {
            brandMapper.insertCategory_Brand(brand.getId(),s);
        }
    }

    public List<Category> getCategoryById(Integer id) {
        List<Category>list= brandMapper.getCategoryById(id);
        return list;
    }

    public void updateBrand(Brand brand, String[] split) {
        brandMapper.updateByPrimaryKey(brand);
        for (String s : split) {
            int i = Integer.parseInt(s);
            brandMapper.deleteByPrimaryKey(i);
        }
        for (String s : split) {
            brandMapper.insertCategory_Brand(brand.getId(),s);
        }
    }

    public List<Brand> getBrandByCid(Integer cid) {
        List<Brand> brandByCid = brandMapper.getBrandByCid(cid);
        return brandByCid;

    }

    public Brand findBrandById(Integer bid) {
        Brand brand=brandMapper.findBrandById(bid);
        return brand;
    }
}
